import { defineStore } from 'pinia'
import { ref } from 'vue'
import { Login, Register, Logout } from '@/api/account'
import { uploadAvatar } from '@/api/upload'
import { updateUser, getUserDetail, changePassword, getUserList, getUserById, getCaptcha } from '@/api/user'

export const useUserStore = defineStore('user', () => {
    const token = ref(localStorage.getItem('token') || '')
    const userInfo = ref(JSON.parse(localStorage.getItem('userInfo') || '{}'))
    const captchaInfo = ref(null)

    // 获取验证码
    const getCaptchaAction = async () => {
        try {
            const response = await getCaptcha()
            if (response.code === 0) {
                captchaInfo.value = response.data
                return Promise.resolve(response)
            } else {
                return Promise.reject(new Error(response.msg))
            }
        } catch (error) {
            return Promise.reject(error)
        }
    }

    // 登录
    const login = async (loginData) => {
        try {
            const response = await Login(loginData)
            if (response.code === 0) {
                token.value = response.data.token
                userInfo.value = response.data.user

                // 存储到localStorage
                localStorage.setItem('token', token.value)
                localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
                // 登录成功后清除验证码信息
                captchaInfo.value = null
                return Promise.resolve(response)
            } else {
                return Promise.reject(new Error(response.msg))
            }
        } catch (error) {
            return Promise.reject(error)
        }
    }

    // 注册
    const register = async (registerData) => {
        try {
            const response = await Register(registerData)
            if (response.code === 0) {
                return Promise.resolve(response)
            } else {
                return Promise.reject(new Error(response.msg))
            }
        } catch (error) {
            return Promise.reject(error)
        }
    }

    // 登出
    const logout = async () => {
        try {
            const response = await Logout()
            return Promise.resolve(response)
        } catch (error) {
            return Promise.reject(error)
        } finally {
            // 清除本地存储
            token.value = ''
            userInfo.value = {}
            localStorage.removeItem('token')
            localStorage.removeItem('userInfo')
        }
    }

    // 检查是否登录
    const isLoggedIn = () => {
        return !!token.value
    }

    // 获取用户ID
    const getUserId = () => {
        return userInfo.value.user_id
    }

    // 获取用户名（优先显示昵称，没有则显示邮箱）
    const getDisplayName = () => {
        return userInfo.value.nickname || userInfo.value.email || '用户'
    }

    // 获取用户邮箱
    const getUserEmail = () => {
        return userInfo.value.email || ''
    }

    // 获取用户头像
    const getUserAvatar = () => {
        return userInfo.value.avatar || ''
    }

    //获取用户验证状态
    const getUserVerifyStatus = () => {
        return userInfo.value.verification_status
    }

    // 检查资料是否完整
    const isProfileComplete = () => {
        return !!(userInfo.value.nickname && userInfo.value.phone && userInfo.value.email)
    }

    // 上传头像
    const uploadUserAvatar = async (file) => {
        try {
            const formData = new FormData()
            formData.append('file', file)

            const response = await uploadAvatar(formData)
            if (response.code === 0) {
                // 更新本地用户信息
                userInfo.value.avatar = response.data.avatar
                localStorage.setItem('userInfo', JSON.stringify(userInfo.value))

                return Promise.resolve(response)
            } else {
                return Promise.reject(new Error(response.msg))
            }
        } catch (error) {
            return Promise.reject(error)
        }
    }

    // 更新用户信息
    const updateUserInfo = async (updateData) => {
        try {
            const userId = userInfo.value.user_id
            const response = await updateUser(userId, updateData)
            if (response.code === 0) {
                // 更新本地用户信息
                userInfo.value = { ...userInfo.value, ...updateData }
                localStorage.setItem('userInfo', JSON.stringify(userInfo.value))

                return Promise.resolve(response)
            } else {
                return Promise.reject(new Error(response.msg))
            }
        } catch (error) {
            return Promise.reject(error)
        }
    }

    // 刷新用户信息
    const refreshUserInfo = async () => {
        try {
            const userId = userInfo.value.user_id
            const response = await getUserDetail(userId)
            if (response.code === 0) {
                userInfo.value = response.data
                localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
                return Promise.resolve(response)
            } else {
                return Promise.reject(new Error(response.msg))
            }
        } catch (error) {
            return Promise.reject(error)
        }
    }

    //修改密码
    const changePasswordAction = async (passwordData) => {
        try {
            const response = await changePassword({
                oldPassword: passwordData.oldPassword,
                newPassword: passwordData.newPassword
            })

            if (response.code === 0) {
                return Promise.resolve(response)
            } else {
                return Promise.reject(new Error(response.msg))
            }
        } catch (error) {
            return Promise.reject(error)
        }
    }

    //获取用户列表
    const getUserListAction = async (params) => {
        try {
            const response = await getUserList(params)
            if (response.code === 0) {
                return Promise.resolve(response)
            } else {
                return Promise.reject(new Error(response.msg))
            }
        } catch (error) {
            return Promise.reject(error)
        }
    }

    //根据id获取用户信息
    const getUserByIdAction = async (userId) => {
        try {
            const response = await getUserById(userId)
            if (response.code === 0) {
                return Promise.resolve(response)
            } else {
                return Promise.reject(new Error(response.msg))
            }
        } catch (error) {
            return Promise.reject(error)
        }
    }
    return {
        token,
        userInfo,
        login,
        register,
        logout,
        isLoggedIn,
        getUserId,
        getDisplayName,
        getUserEmail,
        getUserAvatar,
        getUserVerifyStatus,
        isProfileComplete,
        uploadUserAvatar,
        updateUserInfo,
        refreshUserInfo,
        changePasswordAction,
        getUserListAction,
        getUserByIdAction,
        getCaptchaAction
    }
})